package myServer.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import myServer.session.ServerSession;
import org.springframework.stereotype.Service;

import java.io.IOException;

@ChannelHandler.Sharable
@Service("ServerExceptionHandler")
public class ServerExceptionHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ServerSession.closeChannelBySession(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof Exception) {
            cause.printStackTrace();
            System.out.println(cause.getMessage());
        }
        if (cause instanceof IOException) {
            //远程连接，已经关闭
            System.out.println(cause.getMessage());
            System.out.println("客户端已经关闭连接，这里需要做下线处理");
            ServerSession.closeChannelBySession(ctx);
        } else {
            //捕捉异常信息
            cause.printStackTrace();
            System.out.println(cause.getMessage());
        }
    }

}
